package main

import (
	"embed"
	"fmt"
	"github.com/gin-gonic/gin"
	"gopkg.in/yaml.v2"
	"html/template"
	"io/fs"
	"net/http"
	"runtime"
	"z-blog/database"
	"z-blog/router"
	"z-blog/utils"
)

//go:embed config/config.yaml
var configFile []byte

//go:embed template static
var FS embed.FS

type ConfigModel struct {
	BasicInfo BasicInfo `yaml:"basic_info"`
}

type BasicInfo struct {
	WebPort string `yaml:"web_port"`
}

var (
	port string
)

func init() {
	var configModel ConfigModel
	//初始化配置信息
	err := yaml.Unmarshal(configFile, &configModel)
	if err != nil {
		fmt.Println("引入配置文件信息错误：", err)
		return
	}
	port = configModel.BasicInfo.WebPort
	//检测是否首次打开并创建用户密码
	database.FirstOpen()
}
func main() {
	//获取Panic信息
	defer func() {
		if err := recover(); err != nil {
			for i := 3; ; i++ { //跳过前三层panic信息
				_, file, line, ok := runtime.Caller(i)
				if !ok {
					break
				}
				fmt.Println(file, line)
			}
		}
	}()
	r := gin.Default()
	r.Use(utils.Cors(), utils.Static())
	templ := template.Must(template.New("").ParseFS(FS, "template/*.html"))
	r.SetHTMLTemplate(templ)

	fe, _ := fs.Sub(FS, "static")
	r.StaticFS("/static", http.FS(fe))
	r.GET("/", func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.html", nil)
	})
	routers := router.Router(r)
	err := routers.Run(":" + port)
	if err != nil {
		panic(err)
	}
}
